package com.school.edupoint.token;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.school.edupoint.model.Student;
import com.school.edupoint.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;



@Component
public class TokenManager {

    private final RedisTemplate<String, Object> redisTemplate;

    // 设置 token 有效期（例如 30 分钟）
    private static final long TOKEN_EXPIRE_MINUTES = 3000;

    public TokenManager(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 用户 token 前缀
    private static String userTokenKey(String token) {
        return "token:user:" + token;
    }

    // 学生 token 前缀
    private String studentTokenKey(String token) {
        return "token:student:" + token;
    }

    // 用户登录
    public void put(String token, User user) {
        String key = userTokenKey(token);
        redisTemplate.opsForValue().set(key, user, TOKEN_EXPIRE_MINUTES, TimeUnit.MINUTES);
    }

    public User get(String token) {
        String key = userTokenKey(token);
        Object value = redisTemplate.opsForValue().get(key);

        if (value instanceof User) {
            return (User) value;
        } else if (value instanceof Map) {
            // 处理LinkedHashMap转换问题
            ObjectMapper mapper = new ObjectMapper();
            return mapper.convertValue(value, User.class);
        }
        return null;
    }


    public void remove(String token) {
        String key = userTokenKey(token);
        redisTemplate.delete(key);
    }

    // 学生登录
    public void putStudent(String token, Student student) {
        String key = studentTokenKey(token);
        redisTemplate.opsForValue().set(key, student, TOKEN_EXPIRE_MINUTES, TimeUnit.MINUTES);
    }

    public Student getStudent(String token) {
        String key = studentTokenKey(token);
        Object value = redisTemplate.opsForValue().get(key);

        if (value instanceof Student) {
            return (Student) value;
        } else if (value instanceof Map) {
            // 处理LinkedHashMap转换问题
            ObjectMapper mapper = new ObjectMapper();
            return mapper.convertValue(value, Student.class);
        }
        return null;
    }

    public void removeStudent(String token) {
        String key = studentTokenKey(token);
        redisTemplate.delete(key);
    }

    // 判断 token 是否存在
    public boolean containsUserToken(String token) {
        String key = userTokenKey(token);
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    public boolean containsStudentToken(String token) {
        String key = studentTokenKey(token);
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }
}